package br.com.fromtis.jsf.modal.dao;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.catalina.tribes.tipis.AbstractReplicatedMap.MapOwner;
import org.hibernate.Session;
import org.hibernate.Transaction;
import br.com.fromtis.jsf.modal.entity.Categoria;
import br.com.fromtis.jsf.util.HibernateUtil;





public class CategoriaDao implements IDao<Categoria>,Serializable {
    private static final long serialVersionUID = 1L;
    
    
	private Session session = HibernateUtil.getInstance().getCurrentSession();
	
	@Override
	public List<Categoria> getListEntity () {
		return session.createQuery( "from Categoria" ).list();
	}
	
	@Override
	public void save ( Categoria entity ) {
		Transaction tran = session.beginTransaction();
		session.saveOrUpdate( entity );
		tran.commit();
	}
	
	@Override
	public boolean delete ( Categoria entity ) {
		Transaction tran = null;
		try {
			tran = session.beginTransaction();
			session.delete( entity );
			tran.commit();
			return true;
		} catch ( Exception e ) {
			tran.rollback();
			System.out.println( e.getMessage() );
			return false;
		}
	}
	
	@Override
	public void merge ( Categoria entity ) {
		Transaction tran = session.beginTransaction();
		session.merge( entity );
		tran.commit();
	}
	
	public Map<String, Integer> mapCategoria () {
		Map<String, Integer> mapCategorias = new LinkedHashMap<>();
		for ( Iterator<Categoria> iterator = session.createQuery( "from Categoria" ).iterate(); iterator
		    .hasNext(); ) {
			Categoria cat = iterator.next();
			mapCategorias.put( cat.getDescricao(), cat.getId() );
		}
		return mapCategorias;
	}
	
	@Override
	public Categoria getEntity ( Serializable id ) {
		return (Categoria) session.get( Categoria.class, id );
	}
	
}
